package com.hnhs.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@RestController
@CrossOrigin // 解决跨域访问 只支持 get请求
public class HelloController {
//    @Value("${server.address}")
    @Value("${app.baseUrl}")
    private String baseUrl;

    @Autowired
    private ResourcePatternResolver resolver;

    @GetMapping("/hello")
    public String Hello(){
        System.out.println(baseUrl);
        return "hello springboot:"+baseUrl;
    }
@GetMapping("/list")
public List<String> getImages() throws IOException {
        List<String> imageUrls = new ArrayList<>();
        //扫描 static images
    Resource[] resources = resolver.getResources("classpath:/static/images/*");
    Pattern imagePattern = Pattern.compile(".*\\.(jpg|jpeg|png|gif|bmp|webp)",Pattern.CASE_INSENSITIVE);

    for (Resource resource : resources) {
        System.out.println(resource.getFilename());
        if(resource.isReadable()){
            String filename = resource.getFilename();
            System.out.println(filename);
            if (filename != null && imagePattern.matcher(filename).matches()){
                // http://localhost:8080/images/8.png
                String fullUrl = baseUrl + "/images/" + filename;
                imageUrls.add(fullUrl);

            }
        }
    }
    return imageUrls;
}

}
